package com.chcit.mobile.mvp.shipment.fragment;

import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chcit.custom.view.loader.QuickLoader;
import com.chcit.custom.view.util.DialogUtil;
import com.chcit.hwmsmobile.edittext.SuperEditText;
import com.chcit.mobile.R;
import com.chcit.mobile.app.base.ScanFragment;
import com.chcit.mobile.helper.HttpClientHelper;
import com.chcit.mobile.mvp.common.adapter.DirectScanAdapter;
import com.chcit.mobile.mvp.entity.PackageBean;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.chcit.mobile.mvp.di.component.DaggerDirectShipmentComponent;
import com.chcit.mobile.mvp.shipment.contract.DirectShipmentContract;
import com.chcit.mobile.mvp.shipment.presenter.DirectShipmentPresenter;
import com.xuexiang.xui.widget.toast.XToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 发货登记
 */
public class DirectShipmentFragment extends ScanFragment<DirectShipmentPresenter> implements DirectShipmentContract.View {

    @BindView(R.id.et_hcr_productName)
    SuperEditText etProductName;
    @BindView(R.id.bt_hcr_query)
    Button btQuery;
    @BindView(R.id.lv_hcr_list)
    RecyclerView mRecyclerView;
    @BindView(R.id.bt_hcr_ok)
    Button btOk;
    private String userCode;
    private DirectScanAdapter mAdapter;
    private List<PackageBean> packageBeanList = new ArrayList<>();



    public static DirectShipmentFragment newInstance() {
        DirectShipmentFragment fragment = new DirectShipmentFragment();
        return fragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        DaggerDirectShipmentComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public View initView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getArguments() != null) {
            String mParam1 = getArguments().getString("userCode");
            userCode=mParam1;
        }
        return inflater.inflate(R.layout.fragment_direct_shipment, container, false);
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
          mCommonToolbar.setTitleText("发货登记");
    }


    @Override
    public void setData(@Nullable Object data) {

    }

    @Override
    public void showLoading() {
        QuickLoader.showLoading(mContext);
    }

    @Override
    public void hideLoading() {
        QuickLoader.stopLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        XToast.info(mContext,message).show();
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {

    }

    @Override
    public void onEnterAnimationEnd(Bundle savedInstanceState) {
        super.onEnterAnimationEnd(savedInstanceState);
        initRecyclerView();

    }
    public void initRecyclerView(){
        mAdapter = new DirectScanAdapter(packageBeanList);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

//        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
//            int itemClickPosition = -1;
//
//            @Override
//            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
//
//                if (itemClickPosition >= 0) {
//                    mAdapter.notifyItemChanged(mAdapter.getthisPosition());
//                    mAdapter.setThisPosition(position);
//                    itemClickPosition = position;
//                    // PackageBean packageBean= (PackageBean) adapter.getData().get(position);
//                    mAdapter.notifyItemChanged(mAdapter.getthisPosition());
//                }
//
//            }
//        });

        // int itemClickPosition = -1;
        mAdapter.setOnItemLongClickListener((adapter, view, position) -> {
            if(position >= 0){
                new MaterialDialog.Builder(getContext())
                        .title("提示")
                        .content("是否删除？")
                        .negativeText("删除")
                        .positiveText("取消")
                        .onNegative((dialog, which) -> {
                            mAdapter.remove(position);
                        })
                        .build()
                        .show();
                return false;
            }
            return true;
        });

        mRecyclerView.setAdapter(mAdapter);
    }


    @Override
    protected void onBarcodeEventSuccess(String barcodeData) {
        if(!barcodeData.isEmpty()){
            etProductName.setText(barcodeData);
            btQuery.performClick();
        }
    }

    @OnClick({R.id.bt_hcr_query, R.id.bt_hcr_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_hcr_query:
                getData();
                break;
            case R.id.bt_hcr_ok:
                shipmentPackage();
                break;
        }
    }


    private void getData() {
        if(etProductName.getText().toString().isEmpty()){
            return;
        }
        JSONObject params = new JSONObject();
        params.put("packageNo",etProductName.getText().toString());
        params.put("packageStatus","S");//在库
        params.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
        mPresenter.getPackageInfo(params, list->{
            PackageBean packageBean = new PackageBean();
            packageBean.setPackageNo(etProductName.getText().toString());
            packageBean.setUnitPackQty(list.get(0).getQty());
            packageBean.setQty(list.get(0).getQty());
            packageBean.setProductName(list.get(0).getProductName());
            packageBean.setLot(list.get(0).getLot());
            packageBean.setGuaranteeDate(list.get(0).getGuaranteeDate());
            packageBean.setUomName(list.get(0).getUomName());
            int position = packageBeanList.indexOf(packageBean);
            if(position >= 0){
                new MaterialDialog.Builder(getContext())
                        .title("提示")
                        .content("该条码已被扫过，是否删除？")
                        .negativeText("删除")
                        .positiveText("取消")
                        .onNegative((dialog, which) -> {
                            mAdapter.remove(position);
                        })
                        .build()
                        .show();
                return;
            }
            mAdapter.addData(packageBean);

        });
    }


    public void shipmentPackage() {

        JSONObject params = new JSONObject();
        List<PackageBean> pas=mAdapter.getData();
        if(pas.size()==0){
            DialogUtil.showErrorDialog(getContext(),  "没有数据！");
        return;
        }
        JSONArray packageNoS=new JSONArray();
        for(int i=0;i<pas.size();i++){
            packageNoS.add(pas.get(i).getPackageNo());
        }
        params.put("packageNo",packageNoS);
        params.put("warehouseId", HttpClientHelper.getSelectWareHouse().getId());
        params.put("userCode",userCode);
        assert mPresenter != null;
        mPresenter.shipmentPackageConfirm(params,()->{
            showMessage("登记成功!");
            mAdapter.getData().clear();//清空
            mAdapter.notifyDataSetChanged();//刷新
        });

    }

}
